package com.chianghao.rockframewrok.starter.db;

import javax.sql.DataSource;

import com.chianghao.rockframewrok.core.mybatis.MyBatisSqlSessionFactoryBean;
import com.chianghao.rockframewrok.core.mybatis.plugins.PaginationInterceptor;
import com.chianghao.rockframewrok.starter.db.model.DBHasLoad;
import com.chianghao.rockframewrok.starter.db.properties.MybatisProperties;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnSingleCandidate;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;


@Configuration
@ConditionalOnClass({SqlSessionFactory.class, SqlSessionFactoryBean.class})
@ConditionalOnSingleCandidate(DataSource.class)
@EnableConfigurationProperties({MybatisProperties.class})
@AutoConfigureAfter({DataSourceAutoConfiguration.class})
public class MybatisAutoConfiguration {
	

	@Autowired
    private MybatisProperties properties;
	
	@Autowired
    DBHasLoad dBHasLoad;
	
	
	@Bean
	@ConditionalOnClass(DBHasLoad.class)
    public MyBatisSqlSessionFactoryBean sqlSessionFactory(DataSource dataSource) throws Exception {
		MyBatisSqlSessionFactoryBean factoryBean =new  MyBatisSqlSessionFactoryBean();
		if(StringUtils.isNotEmpty(properties.getConfigLocation())) {
			factoryBean.setConfigLocation(new ClassPathResource(properties.getConfigLocation()));
		}
		factoryBean.setDataSource(dataSource);
		factoryBean.setMapperLocations(properties.resolveMapperLocations());
		PaginationInterceptor paging = new PaginationInterceptor();
		Interceptor[] plugins = {paging};		
		factoryBean.setPlugins(plugins);
		return factoryBean;
	}
	
	@Bean
	public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
		SqlSessionTemplate template = new SqlSessionTemplate(sqlSessionFactory);
		return template;
	}

	
	
}
